package com.dg.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;

/**
 * json工具类，主要提供了【将对象转化成Json字符串】、【json数据转对象】、【将json数据转换成pojo对象list】方法
 */
public class JsonUtil {

    private static final ObjectMapper MAPPER  = new ObjectMapper();

    //将对象转化成Json字符串
    public static String objectToJson(Object object){
        try {
            String value= MAPPER.writeValueAsString(object);
            return value;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    //json数据转对象
    public static <T> T jsonToPojo(String json, Class<T> beanType){
        try {
           T t = MAPPER.readValue(json, beanType);
           return t;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 将json数据转换成pojo对象list
    public static <T> List<T> jsonToList(String json, Class beanType){
        JavaType javaType = MAPPER.getTypeFactory().constructType(beanType);
        try {
            List<T> list=MAPPER.readValue(json, javaType);
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


}
